# -*- coding: utf-8 -*-

from model.gamestate import *
import json
import urllib2
import urllib
import codecs
from constants import JSON_TIMEOUT
from kivy.network.urlrequest import UrlRequest
from kivy.logger import Logger
import os


class CleaningUrlRequest(UrlRequest):
    def __init__(self, file_name, cleanup=False, **kwargs):
        self.file_name = file_name
        self.cleanup = cleanup
        super(CleaningUrlRequest, self).__init__(**kwargs)


def after_error(req, result):
    """ Actions after UrlRequest error
    """
    Logger.debug('Unable to upload json {}'.format(req.file_name))


def after_success(req, result):
    """ Actions after UrlRequest success
    """
    Logger.debug('Uploaded {}'.format(req.file_name))
    if req.cleanup:
        try:
            os.remove(req.file_name)
        except Exception as e:
            Logger.debug('Error while cleaning up file {} - {}'
                         .format(req.file_name, e))


class JsonRoundsCreater():
    def dump_to_url(self, url, json_string,
                    file_name, cleanup=False):
        """ Starts dumping json file to server

        args:
        url: (string) server url
        json_string: (string) json data
        file_name: (string) file, that should be deleted on success
        file_num: (int) file number

        """
        req = CleaningUrlRequest(url=url, timeout=JSON_TIMEOUT,
                                 on_success=after_success,
                                 on_error=after_error, req_body=
                                 urllib.urlencode([('history', json_string)]),
                                 file_name=file_name, cleanup=cleanup)

    def create_json_rounds(self, game_state):
        """ Creating json file to send on server

        args:
            game_state (GameState)
        """
        game_type = game_state.game_type
        settings = game_state.settings
        strategy = game_state.players.players_select_strategy
        pin = game_state.pin_code
        remote_id = game_state.remote_id
        hat = game_state.hat
        rounds = game_state.rounds

        all_json = {
            u'game_type': str(game_type) if game_type else None,
            u'rounds': [],
            u'settings': {
                u'skip_words_per_round': settings.skip_words,
                u'time_before_out_sec': settings.time_before_out_sec,
                u'time_per_round_sec': settings.time_per_round_sec
            },
            u'is_paired_strategy': strategy.is_pair_strategy(),
            u'words_in_hat': []
        }

        if pin is not None:
            all_json[u'pin'] = pin

        if remote_id is not None:
            all_json[u'remote_id'] = remote_id

        for word in hat.words:
            owner_name = None
            if word.owner is not None:
                owner_name = word.owner.name
            all_json[u'words_in_hat'].append({u'text': word.text,
                                              u'owner': owner_name})

        for game_round in rounds:
            json_round = {
                u'words': [],
                u'player1': game_round.players_pair[0].name,
                u'player2': game_round.players_pair[1].name,
                u'time': settings.time_per_round_sec - game_round.time_left_sec
            }
            for word in game_round.words:
                owner_name = None
                if word.word.owner is not None:
                    owner_name = word.word.owner.name
                wgs = {
                    u'text': word.word.text,
                    u'owner': owner_name,
                    u'result': WordGuessResult.text_repr[word.result],
                    u'time': word.time
                }
                json_round[u'words'].append(wgs)
            all_json[u'rounds'].append(json_round)
        return json.dumps(all_json, encoding='utf-8', sort_keys=True)
